package com.example.night.service.ApiService;

import com.example.night.data.SellingGood.SellingGood;
import com.example.night.data.SellingGood.SellingGoodPackage;
import com.example.night.data.SellingGood.SellingGoodResponse;
import com.example.night.service.ApiService.Token.TokenService;
import com.example.night.service.ApiService.Token.TokenUpdatedEvent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class SellingGoodsService {
    private final TokenService tokenService;
    private String token;

    private static final Logger logger = LoggerFactory.getLogger(SellingGoodsService.class);
    private static final String API_URL = "https://api.jiutool.com/institutionHomeTwo/workbench/issue_product";
    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;
    private final Lock lock = new ReentrantLock();

    public SellingGoodsService(TokenService tokenService, RestTemplate restTemplate, ObjectMapper objectMapper) {
        this.tokenService = tokenService;
        this.restTemplate = restTemplate;
        this.objectMapper = objectMapper;
    }

    @EventListener
    public void handleTokenUpdated(TokenUpdatedEvent event) {
        token = event.getNewToken();
    }

    /**
     * 获取所有商品数据（自动遍历分页）
     *
     * @return `List<Good>` 商品列表
     */
    public List<SellingGoodPackage> fetchGoods(String startTime, String endTime, int page) {
        try {
            token = tokenService.getToken();
            if (token == null) {
                logger.error("获取订单数据失败：Token 为空，用户未登录");
                return null;
            }

            List<SellingGood> allSellingGoods = new ArrayList<>();
            List<SellingGoodPackage> sellingGoodPackages = new ArrayList<>();
            int lastPage = 1;

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + token);  // 设置 Authorization 请求头
            headers.set("X-Csrf-Token", token);     // 设置 CSRF Token
            headers.set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

            // 构造请求 URL
            String url = UriComponentsBuilder.fromHttpUrl(API_URL)
                    .queryParam("page", page)
                    .queryParam("limit", 10)
                    .queryParam("sort_type", "")
                    .queryParam("start_time", startTime)
                    .queryParam("end_time", endTime)
                    .queryParam("product_id", "")
                    .queryParam("product_name", "")
                    .toUriString();

            HttpEntity<String> requestEntity = new HttpEntity<>(headers);

//            logger.info("请求第 {} 页商品数据: {}", page, url);

            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
//            logger.info("API 返回数据: {}", response.getBody());

            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                SellingGoodResponse sellingGoodResponse = objectMapper.readValue(response.getBody(), SellingGoodResponse.class);
                if (sellingGoodResponse.getData() != null) {
                    List<SellingGood> sellingGoods = sellingGoodResponse.getData().getGoods();
                    for (SellingGood sellingGood : sellingGoods) {
                        SellingGoodPackage sellingGoodPackage = getSellingGoodPackage(sellingGood);

                        sellingGoodPackages.add(sellingGoodPackage);
                    }
                    allSellingGoods.addAll(sellingGoods);
                    lastPage = sellingGoodResponse.getData().getLastPage();
                }
            } else {
                logger.error("获取商品数据失败，状态码: {}", response.getStatusCode());
            }

//            logger.info("共获取商品数据 {} 条", sellingGoodPackages.size());
            return sellingGoodPackages;

        } catch (Exception e) {
            logger.error("获取商品数据请求失败", e);
            return Collections.emptyList();
        }
    }

    public List<SellingGoodPackage> getResponse(String startTime, String endTime, int page, HttpEntity<String> requestEntity) throws JsonProcessingException {
        String url = UriComponentsBuilder.fromHttpUrl(API_URL)
                .queryParam("page", page)
                .queryParam("limit", 20)
                .queryParam("sort_type", "")
                .queryParam("start_time", startTime)
                .queryParam("end_time", endTime)
                .queryParam("product_id", "")
                .queryParam("product_name", "")
                .toUriString();
        //            logger.info("请求第 {} 页商品数据: {}", page, url);
        List<SellingGoodPackage> sellingGoodPackages = new ArrayList<>();
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
//            logger.info("API 返回数据: {}", response.getBody());

        if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
            SellingGoodResponse sellingGoodResponse = objectMapper.readValue(response.getBody(), SellingGoodResponse.class);

            if (sellingGoodResponse.getData() != null) {
                List<SellingGood> sellingGoods = sellingGoodResponse.getData().getGoods();

                for (SellingGood sellingGood : sellingGoods) {
                    SellingGoodPackage sellingGoodPackage = getSellingGoodPackage(sellingGood);
                    sellingGoodPackages.add(sellingGoodPackage);
                }
            }
            page++;
        }
        return sellingGoodPackages;
    }

    public List<SellingGoodPackage> getGoodsRanking(String startTime, String endTime) {
        try {
            token = tokenService.getToken();
            if (token == null) {
                logger.error("获取订单数据失败：Token 为空，用户未登录");
                return null;
            }

            List<SellingGood> allSellingGoods = new ArrayList<>();
            List<SellingGoodPackage> sellingGoodPackages = new ArrayList<>();
            int lastPage = 1;
            int page = 1;

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + token);
            headers.set("X-Csrf-Token", token);
            headers.set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            HttpEntity<String> requestEntity = new HttpEntity<>(headers);

            String url = UriComponentsBuilder.fromHttpUrl(API_URL)
                    .queryParam("page", page)
                    .queryParam("limit", 20)
                    .queryParam("sort_type", "")
                    .queryParam("start_time", startTime)
                    .queryParam("end_time", endTime)
                    .queryParam("product_id", "")
                    .queryParam("product_name", "")
                    .toUriString();

            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);

            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                SellingGoodResponse sellingGoodResponse = objectMapper.readValue(response.getBody(), SellingGoodResponse.class);
                if (sellingGoodResponse.getData() != null) {
                    List<SellingGood> sellingGoods = sellingGoodResponse.getData().getGoods();
                    for (SellingGood sellingGood : sellingGoods) {
                        SellingGoodPackage sellingGoodPackage = getSellingGoodPackage(sellingGood);
                        sellingGoodPackages.add(sellingGoodPackage);
                    }
                    allSellingGoods.addAll(sellingGoods);
                    lastPage = sellingGoodResponse.getData().getLastPage();
                }
                page++;
            } else {
                logger.error("获取商品数据失败，状态码: {}", response.getStatusCode());
            }

            // 使用线程池来异步获取其余页数的数据
            ExecutorService executorService = Executors.newFixedThreadPool(10); // 线程池大小可调整
            List<Future<List<SellingGoodPackage>>> futures = new ArrayList<>();

            while (page <= lastPage) {
                int currentPage = page;
                Future<List<SellingGoodPackage>> future = executorService.submit(() ->
                        getResponse(startTime, endTime, currentPage, requestEntity)
                );
                futures.add(future);
                page++;
            }

            // 等待所有线程完成，并收集结果
            for (Future<List<SellingGoodPackage>> future : futures) {
                try {
                    sellingGoodPackages.addAll(future.get());
                } catch (Exception e) {
                    logger.error("获取商品数据请求失败", e);
                }
            }

            executorService.shutdown(); // 关闭线程池

            return sellingGoodPackages;

        } catch (Exception e) {
            logger.error("获取商品数据请求失败", e);
            return Collections.emptyList();
        }
    }


    public String getYesterdayDate() {
        LocalDate yesterday = LocalDate.now().minusDays(1); // 获取昨天的日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return yesterday.format(formatter);
    }

    public List<SellingGoodPackage> getYesterdayGoodsRanking() {
        String yesterdayDate = getYesterdayDate();

        return getGoodsRanking(yesterdayDate, yesterdayDate);
    }

    private static SellingGoodPackage getSellingGoodPackage(SellingGood sellingGood) {
        SellingGoodPackage sellingGoodPackage = new SellingGoodPackage();

        sellingGoodPackage.setRelateProductImg(sellingGood.getProductImg());
        sellingGoodPackage.setRelateProductId(sellingGood.getProductId());
        sellingGoodPackage.setRelateProductName(sellingGood.getProductName());
        sellingGoodPackage.setOrderNum(sellingGood.getAllOrderTotal());
        sellingGoodPackage.setOrderMoney(sellingGood.getAllTotalPayAmount());
        return sellingGoodPackage;
    }
}
